package com.pin.zheng.xingmulibrary.util;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;


import com.pin.zheng.xingmulibrary.item.AppInfo;

import java.util.ArrayList;
import java.util.List;

public class AppInfoUtil {
    /**
     * 获取手机已安装应用列表
     *
     * @param ctx
     * @param isFilterSystem 是否过滤系统应用
     * @return
     */
    public static ArrayList<AppInfo> getAllAppInfo(Context ctx, boolean isFilterSystem) {
        ArrayList<AppInfo> appBeanList = new ArrayList<>();
        AppInfo bean = null;

        PackageManager packageManager = ctx.getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (PackageInfo p : list) {
            bean = new AppInfo();
            bean.setIcon(p.applicationInfo.loadIcon(packageManager));
            bean.setLabel(packageManager.getApplicationLabel(p.applicationInfo).toString());
            bean.setPackage_name(p.applicationInfo.packageName);
            int flags = p.applicationInfo.flags;
            // 判断是否是属于系统的apk
            if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0 && isFilterSystem) {
//                bean.setSystem(true);
            } else {
                appBeanList.add(bean);
            }
        }
        return appBeanList;
    }


    //{@add - 获取所有带有桌面属性的APK -
    // 需要获取所有apk 添加permission <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
    public static List<AppInfo> getAllLauncherIconPackages(Context context) {
        List<AppInfo> launcherIconPackageList = new ArrayList<>();

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        //set MATCH_ALL to prevent any filtering of the results
        List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_ALL);
        for (ResolveInfo info : resolveInfos) {
            AppInfo item = new AppInfo();
            item.setPackage_name(info.activityInfo.packageName);
            item.setLabel(info.activityInfo.name);
            item.setIcon(info.activityInfo.loadIcon(context.getPackageManager()));
        }

        return launcherIconPackageList;
    }


    //{@ - 获取所有安装的APK (MATCH_UNINSTALLED_PACKAGES 表示未卸载的APK, 包括APK已被删除但是保留数据的)
    // 需要获取所有apk 添加permission <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
    public static List<AppInfo> getInstalledPackages(Context context) {
        List<AppInfo> installedPackageList = new ArrayList<>();
        List<PackageInfo> installedPackageInfoList = context.getPackageManager().getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);

        for (PackageInfo packageInfo: installedPackageInfoList) {
            LogUtils.e(packageInfo.toString());
//            AppInfo item=new AppInfo();
//            item.setLabel(packageInfo.);
//            installedPackageList.add(packageInfo.packageName);
        }
        return installedPackageList;
    }

    //{@ - 获取所有安装的APK (MATCH_UNINSTALLED_PACKAGES 表示未卸载的APK, 包括APK已被删除但是保留数据的)
    // 需要获取所有apk 添加permission <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
    public static List<AppInfo> getInstalledPackages1(Context context) {
        List<AppInfo> installedPackageList = new ArrayList<>();
        PackageManager pm = context.getPackageManager();
        List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
        for(ApplicationInfo packageInfo:packages){
            if( pm.getLaunchIntentForPackage(packageInfo.packageName) != null ){
                String currAppName = pm.getApplicationLabel(packageInfo).toString();
                LogUtils.e(currAppName);
                if(!("相机".equals(currAppName))){
                    AppInfo item=new AppInfo();
                    item.setLabel(currAppName);
                    item.setPackage_name(packageInfo.packageName);
                    item.setIcon(pm.getApplicationIcon(packageInfo));
                    installedPackageList.add(item);
                }
                //This app is a non-system app
            }
            else{
                //System App
            }
        }
        return installedPackageList;
    }


    /*打开app*/
    @TargetApi(Build.VERSION_CODES.DONUT)
    public static void doStartApplicationWithPackageName(Context ctx, String packagename) {

        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = ctx.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = ctx.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            ctx.startActivity(intent);
        }
    }
}
